using System;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

/// <summary>
/// JsonHelp 的摘要说明
/// </summary>
public class JsonHelp
{
   
    /// <summary>
    /// List&lt;T&gt;转Json 或者单个类转Json
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    /// <returns></returns>
    public static string Obj2Json<T>(T data)//clientInform = JsonHelp.Obj2Json<List<Client>>(c);//泛型列表转json, JsonHelp.Obj2Json<PriceList>(p1)单个类转Json
    {
        try
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(data.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                serializer.WriteObject(ms, data);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// Json转List&lt;T&gt; 或者单个类 
    /// </summary>
    /// <param name="json"></param>
    /// <param name="t"></param>
    /// <returns></returns>    
    public static Object Json2Obj(String json, Type t) //list = (List < FavoriteExpress >)JsonHelp.Json2Obj(u.FavoriteExpress, list.GetType())
    {
        try
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(t);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {

                return serializer.ReadObject(ms);
            }
        }
        catch
        {
            return null;
        }
    }
    /// <summary>
    /// DataTable 转Json
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    public static string DataTable2Json(DataTable dt)
    {
        if (dt.Rows.Count == 0)
        {
            return "";
        }

        StringBuilder jsonBuilder = new StringBuilder();
        // jsonBuilder.Append("{"); 
        //jsonBuilder.Append(dt.TableName.ToString());  
        jsonBuilder.Append("[");//转换成多个model的形式
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonBuilder.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                jsonBuilder.Append("\"");
                jsonBuilder.Append(dt.Columns[j].ColumnName);
                jsonBuilder.Append("\":\"");
                jsonBuilder.Append(dt.Rows[i][j].ToString());
                jsonBuilder.Append("\",");
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("},");
        }
        jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
        jsonBuilder.Append("]");
        //  jsonBuilder.Append("}");
        return jsonBuilder.ToString();
    }
    /// <summary>
    /// JSON转对象
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="json"></param>
    /// <returns></returns>
    public static T Json2Obj<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        using (System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(json)))
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
            return (T)serializer.ReadObject(ms);
        }
    }

    #region // 属性和变量转换
    /// <summary>
    /// 属性转变量
    /// 把"&lt;address&gt;k__BackingField":"1",
    /// 转成"address":"1",
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string AttributeToVariable(string value)
    {
        string p = @"\<([A-Z,a-z,0-9,_]*)\>k__BackingField";
        MatchEvaluator matchEvaluator = new MatchEvaluator(AttributeToVariableMatch);
        Regex reg = new Regex(p);
        bool isfind = reg.IsMatch(value);
        value = reg.Replace(value, matchEvaluator);
        return value;
    }
    private static string AttributeToVariableMatch(Match m)
    {
        return m.Groups[1].Value;
    }

    /// <summary>
    /// 变量转属性
    /// 把"address":"1",
    /// 转成"&lt;address&gt;k__BackingField":"1",
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string VariableToAttribute(string value)
    {
        string p = "\\\"([A-Z,a-z,0-9,_]*)\\\"\\:";
        MatchEvaluator matchEvaluator = new MatchEvaluator(VariableToAttributeMatch);
        Regex reg = new Regex(p);
        bool isfind = reg.IsMatch(value);
        value = reg.Replace(value, matchEvaluator);
        return value;
    }
    private static string VariableToAttributeMatch(Match m)
    {
        return string.Format("\"<{0}>k__BackingField\":", m.Groups[1].Value);
    }

    #endregion // 属性和变量转换

    #region // 格式化日期
    /// <summary>
    /// 将Json序列化的时间由new Date(1373390933250) 或Date(1373390933250)或"\/Date(1373390933250+0800)\/"
    /// 转为2013-07-09 17:28:53
    /// 主要用于传给前台
    /// </summary>
    /// <param name="html"></param>
    /// <returns></returns>
    public static string FormatJsonDate(string value)
    {
        string p = @"(new Date)\(+([0-9,-]+)+(\))";
        MatchEvaluator matchEvaluator = new MatchEvaluator(FormatJsonDateMatch);
        Regex reg = new Regex(p);
        value = reg.Replace(value, matchEvaluator);

        p = @"(Date)\(+([0-9,-]+)+(\))";
        matchEvaluator = new MatchEvaluator(FormatJsonDateMatch);
        reg = new Regex(p);
        value = reg.Replace(value, matchEvaluator);

        p = "\"\\\\\\/" + @"Date(\()([0-9,-]+)([+])([0-9,-]+)(\))" + "\\\\\\/\"";
        matchEvaluator = new MatchEvaluator(FormatJsonDateMatch);
        reg = new Regex(p);
        value = reg.Replace(value, matchEvaluator);

        return value;

    }
    /// <summary>
    /// 将Json序列化的时间由Date(1294499956278+0800)转为字符串
    /// </summary>
    private static string FormatJsonDateMatch(Match m)
    {

        string result = string.Empty;

        DateTime dt = new DateTime(1970, 1, 1);

        dt = dt.AddMilliseconds(long.Parse(m.Groups[2].Value));

        dt = dt.ToLocalTime();

        result = dt.ToString("yyyy-MM-dd HH:mm:ss");

        return result;
    }
    #endregion // 格式化日期
}